package cn.hist.hfp.service;

import cn.hist.hfp.converter.PetConverter;
import cn.hist.hfp.entity.Pet;
import cn.hist.hfp.exception.ResourceNotFoundException;
import cn.hist.hfp.repository.PetRepository;
import cn.hist.hfp.vo.PetVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class PetService {

    @Value(value = "${hfp.page-size.pet}")
    private int pageSize;

    private final
    PetRepository petRepository;

    private final PetConverter petConverter;

    @Autowired
    public PetService(PetRepository petRepository, PetConverter petConverter) {
        this.petRepository = petRepository;
        this.petConverter = petConverter;
    }

    public PetVO findOne(int id) {
        Optional<Pet> optionalPet = petRepository.findById(id);
        if (optionalPet.isPresent()) {
            return petConverter.converter(optionalPet.get());
        }
        throw new ResourceNotFoundException();
    }

    public List<PetVO> findSome(int page, String species) {
        List<Pet> pets;
        if (species == null || "".equals(species)) {
            pets = petRepository.findAll(PageRequest.of(page, pageSize)).getContent();
            return petConverter.converter(pets);
        }
        pets = petRepository.findAllBySpeciesName(species, PageRequest.of(page, pageSize)).getContent();
        return petConverter.converter(pets);
    }

    public int numberOfPages(String species) {
        int number;
        if (species == null || "".equals(species))
            number = petRepository.findAll(PageRequest.of(0, pageSize)).getTotalPages();
        else
            number = petRepository.findAllBySpeciesName(species, PageRequest.of(0, pageSize)).getTotalPages();
        return number <= 0 ? 1 : number;
    }

    public PetVO create(Pet pet) {
        return petConverter.converter(petRepository.saveAndFlush(pet));
    }

    public PetVO update(Pet pet) {
        return petConverter.converter(petRepository.saveAndFlush(pet));
    }

    public int delete(int id) {
        Optional<Pet> optionalPet = petRepository.findById(id);
        optionalPet.ifPresent(petRepository::delete);
        return petRepository.findById(id).isPresent() ? 0 : 1;
    }
}
